<?php
/**
 *  HTTP 定制化请求工具 
 *  @author  wangzhoudong  <wangzhoudong@foxmail.com>
 *  @version    1.0
 *  @date 2015年11月3日
 *
 */

namespace LWJ\Utils;
use LWJ\Utils\HttpClient;

class OAuthHttpClient
{

    private $_access_token;

    public $_config;


    /**
     * OAuthHttpClient constructor.
     * @param $config
     *         grant_type
     *         username
     *         password
     *         client_id
     *         client_secret
     *
     */
    public function __construct($config)
    {
        $this->_config = $config;;
        $this->getToken();

    }

    public function getToken() {
        //初始化Tokent
        if($this->_access_token) {
            return $this->_access_token;
        }
        $cache_key = md5(serialize($this->_config));
        if($access_token = \Cache::get($cache_key)){
            $this->_access_token = $access_token;
        }else{
            $data = HttpClient::request($this->_config['token_url'],[],$this->_config);
            $data = json_decode($data,true);
            if(isset($data['access_token'])) {
                $expires_in = floor($data['expires_in']/60)-2;//提前2分钟过期，防止意外
                $data['timeout'] = time() + $data['expires_in'] - 10;
                \Cache::put($cache_key,$data['access_token'],$expires_in);
                $this->_access_token = $data['access_token'];
            }else{
                return '';
            }
        }
        return $this->_access_token;

    }

    
    /**
     * 普通GET请求
     *
     * @param string $url 请求地址
     * @param array $query GET变量数组
     *
     * return string
     */
    public function query($url, array $query = array(),$timeout=null)
    {
        if(!$this->_access_token) {
            return null;
        }
        $query['access_token'] = $this->_access_token;
        return HttpClient::query($url, $query,$timeout=null);
    }

    public  function request($url, array $query, array $request, array $files = array())
    {
        if(!$this->_access_token) {
            return null;
        }
        $query['access_token'] = $this->_access_token;
        return HttpClient::request($url, $query, $request,$files);
    }
    
   public function put($url, array $query, array $request){
       if(!$this->_access_token) {
           return null;
       }
       $query['access_token'] = $this->_access_token;
       return HttpClient::put($url, $query, $request);
   }
   
   public  function delete($url, array $query, array $request){
       if(!$this->_access_token) {
           return null;
       }
       $query['access_token'] = $this->_access_token;
        return HttpClient::delete($url, $query, $request);
   }
   
    
}